/* NOTICE

Jim - the Java Image Manager, copyright (c) 2005 Grant Gardner 

Jim is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

Jim is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Jim; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

Created on 25/05/2008

NOTICE */

package au.com.lastweekend.jim.util;

import java.awt.geom.AffineTransform;

public class ImageUtils {

    public static AffineTransform rotateAndScale(int x, int y, double iWidth, double iHeight, double cWidth, double cHeight,
            double angle) {

        AffineTransform at = new AffineTransform();
        at.setToTranslation(x, y);

        double ya = iWidth * Math.sin(angle);
        double yb = iHeight * Math.cos(angle);

        double xa = iWidth * Math.cos(angle);
        double xb = -iHeight * Math.sin(angle);

        // Translate bounding rectangle to be all positive values
        double xShift = ((xa < 0) ? xa : 0.0) + ((xb < 0) ? xb : 0.0);
        double yShift = ((ya < 0) ? ya : 0.0) + ((yb < 0) ? yb : 0.0);

        iWidth = Math.abs(xa) + Math.abs(xb);
        iHeight = Math.abs(ya) + Math.abs(yb);

        // Scale to fit
        double scale = getScaleToFit(iWidth, iHeight, cWidth, cHeight);

        xShift = -xShift * scale;
        yShift = -yShift * scale;

        at.translate(xShift, yShift);

        xShift = (cWidth - (iWidth * scale)) / 2.0;
        yShift = (cHeight - (iHeight * scale)) / 2.0;

        at.translate(xShift, yShift);
        at.rotate(angle);
        at.scale(scale, scale);

        return at;
    }

    public static AffineTransform scaleToFit(double iWidth, double iHeight, double cWidth, double cHeight) {

        AffineTransform at = new AffineTransform();
        double scale = getScaleToFit(iWidth, iHeight, cWidth, cHeight);
        at.scale(scale, scale);
        return at;
    }

    public static double getScaleToFit(double iWidth, double iHeight, double cWidth, double cHeight) {

        double scale = 1.0;
        if (cWidth < iWidth) {
            // downscale to the width...
            scale = cWidth / iWidth;
        }

        if (cHeight < iHeight * scale) {
            // downscale to the height
            scale = cHeight / (iHeight);
        }
        return scale;
    }

}
